package com.example.j202411.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.j202411.R;
import com.example.j202411.Model.Books;
import com.example.j202411.views.Activity.BookDetailsActivity;
import com.google.gson.Gson;


import java.util.List;

public class BooksAdapter extends RecyclerView.Adapter<BooksAdapter.BookListViewHolder> {

    private List<Books.ResultData.BookData> books;
    private Context context ;

    public BooksAdapter(List<Books.ResultData.BookData> books , Context context) {
        this.books = books;
        this.context = context ;

    }

    public void updateData(List<Books.ResultData.BookData> list) {
        this.books.clear();
        this.books=list;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public BookListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_book, parent, false);
        return new BookListViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull BookListViewHolder holder, int position) {
        Books.ResultData.BookData book = books.get(position);
        holder.title.setText(book.getTitle());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context , BookDetailsActivity.class);
                Gson gson = new Gson() ;
                intent.putExtra("bookData",gson.toJson(book));
                context.startActivity(intent);
            }
        });

    }

    @Override
    public int getItemCount() {
        return books != null ? books.size() : 0;
    }

    static class BookListViewHolder extends RecyclerView.ViewHolder {
        TextView title;

        BookListViewHolder(View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.title);
        }
    }
}